package com.sql.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author YueGod
 * @since 2023/11/1
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ImportSqlService implements CommandLineRunner {

    private final SqlSessionFactory sessionFactory;

    private static final String filename = "overseas_";

    private static final String path = "E:\\下载\\sq\\overseas_split\\";

    private static final AtomicBoolean flag = new AtomicBoolean(true);

    private static final AtomicInteger suffix_int = new AtomicInteger(0);

    private static final int a = 32;

    private static final ExecutorService executor = Executors.newFixedThreadPool(a);

    public void importsql() {
        for (int i = 0; i < a; i++) {
            executor.execute(this::exec);
        }
    }

    private void exec() {
        Reader reader = null;
        while (true) {
            log.info("开始读取SQL脚本");
            String suffix = String.format("%04d", suffix_int.incrementAndGet());
            String fp = path + filename + suffix + ".sql";
            reader = reader(fp);
            if (reader == null) {
                log.info("所有脚本执行完毕");
                break;
            }
            log.info("开始执行SQL脚本");
            ScriptRunner scriptRunner = new ScriptRunner(sessionFactory.openSession().getConnection());
            scriptRunner.setStopOnError(false);
            scriptRunner.setThrowWarning(false);
            scriptRunner.setAutoCommit(true);
            scriptRunner.setFullLineDelimiter(true);
            try {
                scriptRunner.runScript(reader);
            }catch (Exception ignore){
                log.error("123",ignore);

            }

            new File(fp).delete();
        }
    }

    private BufferedReader reader(String fp) {
        log.info("脚本路径: {}", fp);
        try {
            return new BufferedReader(new FileReader(fp));
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void run(String... args) throws Exception {
        Thread.sleep(5000);
        importsql();
    }
}
